package com.lottery.game.runner.v2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.game.common.constants.GameConstants;
import com.lottery.game.common.utils.DateUtils;
import com.lottery.game.core.configuration.SftpUtils;
import com.lottery.game.core.modules.entity.user.ChatRecord;
import com.lottery.game.core.modules.entity.user.UserRankPojo;
import com.lottery.game.core.modules.entity.user.WebsocketMessage;
import com.lottery.game.core.modules.service.app.ChatRecordService;
import com.lottery.game.core.modules.service.app.OnlineAppContext;
import com.lottery.game.core.modules.service.app.OperationalSetService;
import com.lottery.game.core.modules.service.app.UserRankService;
import com.lottery.game.core.modules.service.app.WebSocketService;
import com.lottery.game.core.modules.service.app.WebsocketMessageService;
import com.lottery.game.core.modules.service.game.SysDictService;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 替代com.runshang.apps.cloudgame.runner.RobotManager
 * 
 * @author Jake
 *
 */
@Slf4j
@Component
public class RobotExecutor implements Runnable {

	@Autowired
	private OperationalSetService operationalSetService;

	@Autowired
	private ChatRecordService chatRecordService;

	@Autowired
	private WebSocketService webSocketService;

	@Autowired
	private WebsocketMessageService websocketMessageService;

	@Autowired
	private OnlineAppContext context;

	@Autowired
	private SysDictService sysDictService;

	@Autowired
	private UserRankService userRankService;

	@Override
	public void run() {
		Random random = new Random();
		while (true) {
			try {
				int pmin = 1;
				int psize = 3;
				int pmax = 200;
				final Result result = new Result(pmin, psize, pmax);
				final RobotCount robotCount = new RobotCount();
				Map<String, Object> resultMap = operationalSetService.queryDictRobot();
				if (resultMap != null) {
					pmin = Integer.parseInt((String) resultMap.get("min"));
					psize = Integer.parseInt((String) resultMap.get("size"));
					pmax = Integer.parseInt((String) resultMap.get("max"));

					result.setPmin(pmin);
					result.setPsize(psize);
					result.setPmax(pmax);
				}
				int r = random.nextInt(result.getPmax()) + result.getPmin();// 获取线程休眠的时间

				log.info("{}秒后更新机器人信息!", r);

				TimeUnit.SECONDS.sleep(r);

				if (log.isDebugEnabled()) {
					log.debug("开始推送机器人信息，当前时间{}！", DateUtils.getNowDateString());
				}
				final Integer randomRobotCount = random.nextInt(result.getPsize()) + 1;// 获取随机的机器人个数
				// 获取房间的信息
				List<String> roomList = operationalSetService.queryRoomId();

				if (CollectionUtils.isEmpty(roomList)) {
					// 如果没有对应的room 就休息5秒重新开始
					TimeUnit.SECONDS.sleep(5);
					continue;
				} else {
					log.info("---here---size: {}", roomList.size());
					int i = 1;
					for (String roomNumber : roomList) {
						log.info("获取第【{}】次, 房间编号【{}】", i++, roomNumber);
						List<Map<String, Object>> robotList = operationalSetService.queryRobotData(roomNumber);
						if (!CollectionUtils.isEmpty(robotList)) {
							final Map<String, Integer> chatRobotResult = new ConcurrentHashMap<>();
							chatRobotResult.put("getrobot", 0);
							chatRobotResult.put("m", 0);
//							AtomicInteger getrobot = new AtomicInteger(0);// 记录上传循环的结果
//							int m = 0;// 记录以及随机了多少个机器人

							if (robotList.size() <= result.getPsize()) {
								for (Map<String, Object> robot : robotList) {
									String roomNum = (String) robot.get("roomNumber");
									String robotName = (String) robot.get("robotName");
									String robotLv = (String) robot.get("userLv");
									String robotIcon = (String) robot.get("robotIcon");
									sendMsgToRoom(roomNum, robotName, robotLv, robotIcon);// 往房间里面推送机器人信息
									int sleepTime = (random.nextInt(5) + 5);
									log.info("----1111----休息时间: {}秒", sleepTime);
									TimeUnit.SECONDS.sleep(sleepTime);
								}
							} else {
								for (Map<String, Object> robot : robotList) {
									int robots = random.nextInt(robotList.size());

									while (true) {
										if (robots == robotCount.getCount().intValue()) {
											robots = random.nextInt(robotList.size());
										} else {
											int current = robotCount.getCount().get();
											robotCount.getCount().getAndAdd(robots - current);
											break;
										}
									}
									String roomNum = (String) robot.get("roomNumber");
									String robotName = (String) robot.get("robotName");
									String robotLv = (String) robot.get("userLv");
									String robotIcon = (String) robot.get("robotIcon");
									sendMsgToRoom(roomNum, robotName, robotLv, robotIcon);// 往房间里面推送机器人信息
									int sleepTime = (random.nextInt(5) + 5);

									TimeUnit.SECONDS.sleep(sleepTime);
									log.info("----2222----休息时间: {}秒", sleepTime);

									robotCount.getRobotCount().incrementAndGet();
									if (robotCount.getRobotCount().intValue() == randomRobotCount.intValue()) {
										if (!Thread.currentThread().isInterrupted()) {
											Thread.currentThread().interrupt();
										}
										break;
									}
								}
//								robotList.forEach(robot -> {
//
//									int robots = random.nextInt(robotList.size());
//
//									while (true) {
//										if (robots == robotCount.getCount().intValue()) {
//											robots = random.nextInt(robotList.size());
//										} else {
//											int current = robotCount.getCount().get();
//											robotCount.getCount().getAndAdd(robots - current);
//											break;
//										}
//									}
//									String roomNum = (String) robot.get("roomNumber");
//									String robotName = (String) robot.get("robotName");
//									String robotLv = (String) robot.get("userLv");
//									String robotIcon=(String) robot.get("robotIcon");
//									sendMsgToRoom(roomNum, robotName, robotLv,robotIcon);// 往房间里面推送机器人信息
//									int sleepTime = (random.nextInt(5)+5);
//
//									try {
//										TimeUnit.SECONDS.sleep(sleepTime);
//									} catch (InterruptedException e) {
//										e.printStackTrace();
//									}
//
//									robotCount.getRobotCount().incrementAndGet();
//									if (robotCount.getRobotCount().intValue() == randomRobotCount.intValue()) {
//										break;
//									}
//
//								});
							}
						}
					}
//					roomList.forEach(roomNumber -> {
//						List<Map<String, Object>> robotList = operationalSetService.queryRobotData(roomNumber);
//						if(!CollectionUtils.isEmpty(robotList)) {
//							final Map<String, Integer> chatRobotResult = new ConcurrentHashMap<>();
//							chatRobotResult.put("getrobot", 0);
//							chatRobotResult.put("m", 0);
////							AtomicInteger getrobot = new AtomicInteger(0);// 记录上传循环的结果
////							int m = 0;// 记录以及随机了多少个机器人
//
//							if (robotList.size() <= result.getPsize()) {
//								robotList.forEach(robot -> {
//									String roomNum = (String) robot.get("roomNumber");
//									String robotName = (String) robot.get("robotName");
//									String robotLv = (String) robot.get("userLv");
//									String robotIcon=(String) robot.get("robotIcon");
//									sendMsgToRoom(roomNum, robotName, robotLv,robotIcon);// 往房间里面推送机器人信息
//
//									try {
//										int sleepTime = (random.nextInt(5) + 5);
//										TimeUnit.SECONDS.sleep(sleepTime);
//									} catch (InterruptedException e) {
//										e.printStackTrace();
//									}
//								});
//							} else {
//								robotList.forEach(robot -> {
//
//									int robots = random.nextInt(robotList.size());
//
//									while (true) {
//										if (robots == robotCount.getCount().intValue()) {
//											robots = random.nextInt(robotList.size());
//										} else {
//											int current = robotCount.getCount().get();
//											robotCount.getCount().getAndAdd(robots - current);
//											break;
//										}
//									}
//									String roomNum = (String) robot.get("roomNumber");
//									String robotName = (String) robot.get("robotName");
//									String robotLv = (String) robot.get("userLv");
//									String robotIcon=(String) robot.get("robotIcon");
//									sendMsgToRoom(roomNum, robotName, robotLv,robotIcon);// 往房间里面推送机器人信息
//									int sleepTime = (random.nextInt(5)+5);
//
//									try {
//										TimeUnit.SECONDS.sleep(sleepTime);
//									} catch (InterruptedException e) {
//										e.printStackTrace();
//									}
//
//									robotCount.getRobotCount().incrementAndGet();
//									if (robotCount.getRobotCount().intValue() == randomRobotCount.intValue()) {
//										return;
//									}
//
//								});
//							}
//						}
//					});
				}
			} catch (Exception e) {
				log.error("机器人推送异常", e);
			}
		}

	}

	/**
	 *
	 * @param roomNuber
	 * @param robotName
	 * @param robotLv
	 * @param robotIcon
	 */
	private void sendMsgToRoom(String roomNuber, String robotName, String robotLv, String robotIcon) {
		String now = DateUtils.getNowDateString();
		Map<String, Object> msgMap = new HashMap<>();
		Map<String, String> paraMap = new HashMap<>();
		Map<String, String> paramMap = new HashMap<>();
		paraMap.put("mySendTime", now);
		paraMap.put("robotName", robotName);
		paraMap.put("robotLv", robotLv);
		paraMap.put("nowTime", now);

		// 获取机器人等级信息
		UserRankPojo userRankPojo = null;
		if (org.apache.commons.lang3.StringUtils.isNotBlank(robotLv)) {
			UserRankPojo userRank = new UserRankPojo();
			userRank.setLevelno(robotLv);
			userRankPojo = userRankService.getUserRank(userRank);
			paraMap.put("level_photourl", userRankPojo == null ? ""
					: sysDictService.findImageServerAddress() + userRankPojo.getLevelPhotourl());
		}
		//msgMap.put("robotMessage", paraMap);
		// 数据库使用
		String robotIconUrl = sysDictService.findImageServerAddress() + robotIcon;
		paramMap.put("roomNumber", roomNuber);
		paramMap.put("sendernickname", robotName);
		paramMap.put("fristSend", "true");
		paramMap.put("message", robotLv);
		paramMap.put("photourl", robotIconUrl);
		paramMap.put("mySendTime", now);
		msgMap.put("robotInfo", paraMap);

		ChatRecord chatRecord = new ChatRecord();

		String uuid = UUID.randomUUID().toString();
		chatRecord.setId(uuid);
		chatRecord.setSenderUserid("robotInfo");
		chatRecord.setRoomnumber(roomNuber);
		String msg = JSON.toJSONString(paramMap);
		chatRecord.setMsgContent(msg);
		chatRecord.setSendernickname(robotName);
		chatRecord.setTimestamp(now);
		chatRecord.setSenderphoto(robotIcon);
		chatRecord.setMessageStatus("0");
		chatRecord.setChatType("0");
		chatRecord.setOrginMsg(robotLv);
		chatRecord.setLevel_photourl(userRankPojo == null ? "" : userRankPojo.getLevelPhotourl());
		String sendMsg = JSONObject.toJSONString(msgMap);

		Set<String> userIdList = context.getUserIdsByRoomNumber(roomNuber);

		if (!CollectionUtils.isEmpty(userIdList))
			userIdList.forEach(userId -> {
				// 推送消息
				webSocketService.sendToTheUser(sendMsg, userId, null, null);
				// 保存消息数据
				websocketMessageService.saveWebsocketMessage2(robotName, sendMsg, userId, roomNuber, "0",
						GameConstants.GAME_STATUS_MAINTAIN, GameConstants.WEBSOCKET_MESSAGE_STATUS_CREATE);
			});

		chatRecordService.addChatRecord(chatRecord);
	}

	public static boolean CheckRandom(int c[], int t, int l) {// 检查生成的随机数是否存在与数组中
		for (int i = 0; i < c.length; i++) {
			if (c[i] == t && l != i) {
				return false;
			}
		}
		return true;
	}

	@AllArgsConstructor
	@Data
	public class Result {
		private Integer pmin;
		private Integer psize;
		private Integer pmax;
	}

	@Data
	public class RobotCount {

		public AtomicInteger count = new AtomicInteger(0);

		public AtomicInteger robotCount = new AtomicInteger(0);
	}
}
